package com.example.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.usercenter.Exception.BusinsessException;
import com.example.usercenter.common.BaseResponse;
import com.example.usercenter.common.ErrorCode;
import com.example.usercenter.common.ResultUtils;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.model.request.UserLoginRequest;
import com.example.usercenter.model.request.UserRegisterRequest;
import com.example.usercenter.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.usercenter.constant.UserConstant.USERLOGINSTATUS;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
            throw new BusinsessException(ErrorCode.NULL_ERROR);
        }
        long l = userService.userRegister(userAccount,userPassword,checkPassword,planetCode);
        return ResultUtils.success(l);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest){
        if (userLoginRequest == null){
            throw new BusinsessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        User user = userService.userLogin(userAccount,userPassword,httpServletRequest);
        return ResultUtils.success(user);
    }

    @GetMapping("/tags")
    public BaseResponse<List<User>> searchUserByTags(List<String> tagNanmeList){
        if (CollectionUtils.isEmpty(tagNanmeList)){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        List<User> userList = userService.searchUsesrByTags(tagNanmeList);
        return ResultUtils.success(userList);
    }

    @GetMapping("/search")
    public List<User> searchUsers(String username, HttpServletRequest request){
        if (!userService.isAdmin(request)){
            return new ArrayList<>();
        }
        if (username == null){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        QueryWrapper query = new QueryWrapper();
        query.like("username",username);
        List<User> list = userService.list(query);
        return list.stream().map(user -> {
            user.setUserPassword(null);
            return user;
        }).collect(Collectors.toList());
    }
    @GetMapping("/delete")
    public BaseResponse<Boolean> searchUsers(@RequestBody long id, HttpServletRequest request){
        if (!userService.isAdmin(request)){
            throw new BusinsessException(ErrorCode.NOT_AUTHOR);
        }
        if (id < 0){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }
    /**
     *用户推荐
     */
    @GetMapping("/recommend")
    public BaseResponse<Page> recommendUser(long page,long pageSize,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(USERLOGINSTATUS);
        String redisKey = String.format("yupaopao:%s", user.getId());
        ValueOperations operations = redisTemplate.opsForValue();
        Page<User> userlist = (Page<User>) operations.get(redisKey);
        if (userlist != null){
            return ResultUtils.success(userlist);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        userlist = userService.page(new Page<>(page, pageSize), queryWrapper);
        try {
            operations.set(redisKey,userlist,1000, TimeUnit.MILLISECONDS);
        }catch (Exception e){

        }
        return ResultUtils.success(userlist);
    }
    /**
     *更新用户信息
     */
    @GetMapping("/update")
     public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        if (user == null){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        Integer result = userService.updateUser(user,request);
        return ResultUtils.success(result);
    }

}